<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>websocket它是html5提供</title>
</head>

<body>
  <div id="root"></div>

  <div>
    <input type="text" oninput="setMsg(this)" id="msg">
    <button onclick="send()">发送数据</button>
  </div>
  <script>
    let msg = ''
    let ws = new WebSocket('ws://localhost:8080/')

    // 接受数据事件
    ws.onmessage = function (evt) {
      document.querySelector('#root').innerHTML += `<div>${evt.data}</div>`
    }

    function setMsg(obj) {
      msg = obj.value
    }

    // 发送数据
    function send() {
      ws.send(msg)
      msg = ''
      document.getElementById('msg').value = msg
    }


  </script>


</body>

</html>